import React, { useState, useEffect } from 'react';

import { custom_search, custom_del, custom_changeleader, custom_delmany } from '../../../utils/api'

import { message, Input, Button, Space, Table, Modal, Upload, Form } from 'antd';
var { Search } = Input;
function CustomManage(props) {

    //引入组件状态
    //表格数据
    var [data, setData] = useState([])
    //最新页码
    var [current, setCurrent] = useState(1)
    //总数
    var [total, setTotal] = useState(50)
    //每页条数
    var [pageSize, setPageSize] = useState(4)
    // 搜索内容
    var [searchKey, setSearchKey] = useState('')
    //  loading 动画
    var [loading, setLoading] = useState(false)
    // 控制消息确认框显示隐藏
    const [delopen, setDelOpen] = useState(false);
    // 控制负责人确认框显示隐藏
    const [leaderopen, setLeaderOpen] = useState(false);

    // 选中的信息
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);

    // 模糊搜素
    const onSearch = (value) => {
        setSearchKey(value)
        setLoading(true)
        custom_search({ searchKey: value, page: current, count: pageSize }).then((res) => {
            if (res.data.code == 200) {
                setData(res.data.list);
                setTotal(res.data.total);
                setLoading(false);
            }
        })
    };

    // 删除单个客服信息
    const deleteCustom = (_id) => {
        console.log(_id);
        custom_del({ id: _id, searchKey, page: current, count: pageSize }).then((res) => {
            message.success('删除成功');
        })
    }
    // 批量选择客服信息
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    // 删除弹框
    const delshowModal = () => {
        setDelOpen(true);
    };
    const delhandleCancel = () => {
        setDelOpen(false);
    };
    // 删除批量选择客服信息
    const delhandleOk = () => {
        setDelOpen(false);
        custom_delmany({ keys: selectedRowKeys, searchKey, page: current, count: pageSize }).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                setData(res.data.list);
                setTotal(res.data.total);
                message.success('删除成功');
            }
        })
    };

    // 更改负责人弹框
    const leadershowModal = () => {
        setLeaderOpen(true);
    };
    const leaderhandleCancel = () => {
        setLeaderOpen(false);
    };
    const leaderFinish = (value) => {
        custom_changeleader({leader:value.leader, keys: selectedRowKeys, searchKey, page: current, count: pageSize }).then((res) => {
            if (res.data.code == 200) {
                setData(res.data.list);
                setTotal(res.data.total);
                message.success('更改成功');
            }
        })
    }

    // 上传文件状态改变
    const onUploadChange = (res) => {
        if (res.file.status == 'done') { //等到 上传完成 才提示上传结果
            if (res.file.response && res.file.response.code == 200) {
                message.success({ message: res.file.response.msg })
            } else {
                message.error({ message: "上传失败!" })
            }
        }
    }

    // =========================================
    //表格分页
    const onChange = ({ current, pageSize, total }) => {
        setCurrent(current);//保存最新页码
        setLoading(true)
        //请求最新页码对应的列表
        custom_search({ searchKey, page: current, count: pageSize }).then((res) => {
            if (res.data.code == 200) {
                setData(res.data.list);
                setTotal(res.data.total);
                setLoading(false);
            }
        })
    };
    // 引入生命周期
    useEffect(() => {
        //获取客服列表
        setLoading(true);
        custom_search({ searchKey, page: current, count: pageSize }).then((res) => {
            setData(res.data.list);
            setTotal(res.data.total);
            setLoading(false)
        })
    }, [])
    // 表格列信息
    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
        },
        {
            title: '地址',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: '负责人',
            dataIndex: 'leader',
            key: 'leader',
        },
        {
            title: '呼入时间',
            dataIndex: 'time',
            key: 'time',
        },

        {
            title: '操作',
            key: 'action',
            render: (text) => (
                <Space size="middle">
                    <i className='iconfont icon-shanchu' onClick={() => { deleteCustom(text._id) }}></i>
                </Space>
            ),
        },
    ];
    //上传请求头
    const headers = { Authorization: 'Bearer ' + localStorage.getItem('token') };

    return (
        <div className='custommange'>
            <h2>客户管理</h2>
            <div className='search'>
                <Search
                    placeholder="输入员工姓名"
                    onSearch={onSearch}
                    style={{ width: 320 }}
                    enterButton
                />
            </div>

            {/* 功能区域 */}
            <div className="opr">
                <Space>
                    <Button disabled={selectedRowKeys.length == 0}>创建人工外呼</Button>
                    <Button disabled={selectedRowKeys.length == 0}>写入机器外呼</Button>
                    <Button disabled={selectedRowKeys.length == 0}>发送消息</Button>
                    <Button disabled={selectedRowKeys.length == 0} onClick={leadershowModal}>设定负责人</Button>
                    <Button disabled={selectedRowKeys.length == 0} onClick={delshowModal}><span className='iconfont icon-shanchu'></span></Button>
                </Space>
                <Space>
                    {/* action 上传地址(导入地址) */}
                    {/* name 上传文件参数名,必须是excel */}
                    {/* headers 上传请求头 */}
                    {/* data 上传所需的额外参数 , 例如: id */}
                    {/* onChange 上传状态发生改变的回调 */}
                    {/* accept 过滤文件类型 */}
                    <Upload
                        action="/api/custom/import"
                        name='excel'
                        headers={headers}
                        onChange={onUploadChange}
                        accept=".xls,.xlsx">
                        <Button type='primary'>导入客户</Button>
                    </Upload>

                    {/* Button组件 指定 href 跳转地址, 最终会渲染为a标签, 点击时会走请求代理(浏览器帮我们发的请求),但是不会走axios二次封装 */}
                    <Button type='primary' href="/api/custom/export">导出客户</Button>

                </Space>
            </div>
            
            {/* 表格 */}
            <Table loading={loading} columns={columns} dataSource={data}
                pagination={{ current, pageSize, total }} onChange={onChange}
                rowSelection={{ selectedRowKeys, onChange: onSelectChange }} />

            {/* 消息确认框 */}
            <Modal
                title="信息确认框"
                open={delopen}
                onOk={delhandleOk}
                onCancel={delhandleCancel}
                okText="确认"
                cancelText="取消"
            >
                <p>亲，确认删除所选客户吗？</p>
            </Modal>
            {/* 设置负责人 */}
            <Modal
                title="修改负责人"
                footer={null}
                open={leaderopen}
                onCancel={leaderhandleCancel}
                okText="确认"
                cancelText="取消"
            >
                <Form onFinish={leaderFinish}>
                    <Form.Item
                        name="leader"
                        rules={[
                            {

                                required: true,
                                message: '请输入新负责人',
                            },
                        ]}
                    >
                        <Input placeholder="请输入新负责人" />
                    </Form.Item>

                    <Form.Item>
                        <Button block type="primary" htmlType="submit" shape="round">
                            确认更新
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div >
    );
}

export default CustomManage;